package edu.yuhf.dbutil;

import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.yuhf.jdbcpart.DBConnection;

public class JdbcTemplate {
	
	public static int update(String sql,Object...param) {
		int rowNum=0;
		Connection connection=DBConnection.getConnection(); 
		try {
			PreparedStatement psmt=connection.prepareStatement(sql);
			ParameterMetaData pmd=psmt.getParameterMetaData();
			if (null!=param&&param.length!=0&pmd.getParameterCount()==param.length) {
				for(int i=0,len=param.length;i<len;i++) {
					psmt.setObject(i+1,param[i]);
				}
			}
			rowNum=psmt.executeUpdate();
		}catch(SQLException e){
			System.out.println("query operation error,message is "+e.getMessage());
		}finally {
			DBConnection.closeConnection(connection);
		}
		return rowNum;
	}
	
	public static int queryForCount(String sql, Object...param) {
	 	   int rowNum=0;
	 			
	 		return rowNum;
	  }
	
	
	public static <T> T query(String sql,ResultSetHandler<T> rsh,Object...param) {
		T t=null;
		Connection connection=DBConnection.getConnection();
		try {
			PreparedStatement psmt=connection.prepareStatement(sql);
			ParameterMetaData pmd=psmt.getParameterMetaData();
			if(null!=param&&param.length!=0&pmd.getParameterCount()==param.length) {
			 		for(int i=0,len=param.length;i<len;i++) {
			 			psmt.setObject(i+1, param[i]);
			 		}
			 }
			 ResultSet rs=psmt.executeQuery();
			 t=rsh.handler(rs);
		} catch (SQLException e) {
			 System.out.println("update operation error,message is "+e.getMessage());
		} finally {
			 DBConnection.closeConnection(connection);
		}		
		return t;
	}
}
